package com.sk.bilibili.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sk.bilibili.event.BiliBiliEvent;
import com.sk.bilibili.other.R;
import com.sk.bilibili.utils.QueryWrapperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import com.sk.bilibili.bean.Danmu;
import com.sk.bilibili.mapper.DanmuMapper;

import java.util.List;

/**
* @author 邵康
* @date 2021/11/26 19:24
*/
@Service
public class DanmuService extends ServiceImpl<DanmuMapper,Danmu> {

    @Autowired
    private ApplicationEventPublisher eventPublisher;

    public R<Void> add(Danmu danmu) {
        eventPublisher.publishEvent(new BiliBiliEvent<>(this,danmu));
        save(danmu);
        return R.success();
    }

    public R<Void> delete(Integer id) {
        removeById(id);
        return R.success();
    }

    public R<Void> update(Danmu danmu) {
        updateById(danmu);
        return R.success();
    }

    public R<IPage<Danmu>> page(Integer page, Integer size) {
        return R.success(page(new Page<>(page,size),null));
    }

    public R<Object[][]> getAll(Integer videoId) {
        QueryWrapper<Danmu> queryWrapper = QueryWrapperUtils.eq("video_id", videoId);
        List<Danmu> list = list(queryWrapper);
        Object[][] res=new Object[list.size()][];
        for (int i = 0; i < res.length; i++) {
            Danmu danmu = list.get(i);
            res[i]=covert(danmu);
        }
        return R.danmu(res);
    }

    private Object[] covert(Danmu danmu) {
        Object[] res=new Object[5];
        res[0]=danmu.getTime();
        res[1]=danmu.getType();
        res[2]=danmu.getColor();
        res[3]=String.valueOf(danmu.getMemberId());
        res[4]=danmu.getContent();
        return res;
    }

    public R<List<Danmu>> getAllDanmu(Integer videoId) {
        QueryWrapper<Danmu> queryWrapper = QueryWrapperUtils.eq("video_id", videoId);
        return R.success(list(queryWrapper));
    }

}
